package com.atguigu.spzx.manager.interceptor;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.exception.GuiguException;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.util.AuthContextUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author LT
 * @create 2024-03-10-16:48
 */
@Component
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取请求方式
        String method = request.getMethod().toUpperCase();
        if ("OPTIONS".equals(method)){
            return true;
        }

        //获取请求头
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            throw new GuiguException(ResultCodeEnum.LOGIN_TOKEN_ERROR);
        }


        //如果token不为空，那么此时验证token的合法性
        String sysUserInfoJson = redisTemplate.opsForValue().get("user:login:" + token);
        if (StringUtils.isEmpty(sysUserInfoJson)) {
            throw new GuiguException(ResultCodeEnum.LOGIN_STATUS_ERROR);
        }

        //将用户数据存储到ThreadLocal中
        SysUser sysUser = JSON.parseObject(sysUserInfoJson, SysUser.class);
        AuthContextUtil.set(sysUser);

        //重置Redis中的用户数据的有效时间
        //redisTemplate.expire("user:login:" + token,60, TimeUnit.MINUTES);

        //放行
        return true;
    }
    public static SysUser getSysUser(){
        return AuthContextUtil.get();
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthContextUtil.remove();  //移除threadLocal中的数据
    }
}
